package com.aaa.sso.service.impl;

import com.aaa.common.bo.User;
import com.aaa.common.util.JWTUtils;
import com.aaa.common.util.Result;
import com.aaa.sso.service.AuthService;
import com.aaa.sso.service.RemoteUserService;
import com.aaa.sso.util.CustomUsernamePasswordToken;
import com.aaa.sso.util.LoginType;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Xiujie Yu
 * @Date 2021-01-21
 * @Time 14:47
 */
@Service("authUserService")
public class AuthUserServiceImpl implements AuthService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RemoteUserService remoteUserService;

    @Override
    public Result<Map<String, Object>> authUserMember(String userName, String password) {
        Result<Map<String, Object>> result = new Result<>();
        //收集用户信息
        CustomUsernamePasswordToken usernamePasswordToken = new CustomUsernamePasswordToken(userName, password, LoginType.USER.toString());
        //获取用户主体 subject 当前登陆用户（shiro）
        Subject subject = SecurityUtils.getSubject();
        //实例化返回的Map
        Map<String, Object> resultMap = new HashMap<>();
        try {
            subject.login(usernamePasswordToken);
            //获取用户信息
            User user = (User) subject.getPrincipal();
            HashMap<String, String> map = new HashMap<>();
            map.put("id", user.getUserId() + "");
            map.put("name", user.getLoginName());
            map.put("username", user.getUserName());
            map.put("type", "user");
            map.put("deptId", user.getDeptId() + "");
            String token = JWTUtils.initToken(30, map);
            resultMap.put("loginSuccess", token);
            resultMap.put("id", user.getUserId() + "");
            resultMap.put("name", user.getLoginName());
            resultMap.put("username", user.getUserName());
            resultMap.put("avatar", user.getAvatar());
            result.setResultMessage("认证通过");
            result.setResultCode(200);
            redisTemplate.opsForValue().set(token, user, 30, TimeUnit.DAYS);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            result.setResultMessage("用户名或密码错误");
            result.setResultCode(500);
            resultMap.put("loginFail", "用户名或密码错误");
        }
        result.setT(resultMap);
        return result;
    }
    /*public Result<Map<String, Object>> authUserMember(String userName, String password) {
        //收集用户信息
        CustomUsernamePasswordToken usernamePasswordToken = new CustomUsernamePasswordToken(userName, password, LoginType.USER.toString());
        //获取用户主体 subject 当前登陆用户（shiro）
        Subject subject = SecurityUtils.getSubject();
        //实例化返回的Map
        Map<String, Object> resultMap = new HashMap<>();
        //登陆
        try {
            subject.login(usernamePasswordToken);
            //获取用户信息
            User user = (User) subject.getPrincipal();
            LoginUserInfo loginUserInfo = new LoginUserInfo();
            loginUserInfo.setLoginName(user.getLoginName());
            loginUserInfo.setHeadPic(user.getAvatar());
            resultMap.put("loginUserInfo",loginUserInfo);
            //认证成功，生成token
            String token = userName+System.currentTimeMillis();
            // 放入redis集群
            redisTemplate.opsForValue().set(token,user,60, TimeUnit.MINUTES);

            resultMap.put("token",token);
            //记录登陆日志
            return new Result<>(ResultStatus.SUCCESS.getCode(),
                    ResultStatus.SUCCESS.getMessage(),
                    resultMap);

        } catch (AuthenticationException e) {
            e.printStackTrace();
            resultMap.put("loginFail", "用户名或密码错误");
        }

        return new Result<>(ResultStatus.FAIL.getCode(),
                ResultStatus.FAIL.getMessage(),
                resultMap);
    }*/

    @Override
    public boolean checkToken(String token) {
        return JWTUtils.verifyToken(token);
    }

    /**
     * 修改用户的密码
     *
     * @param username    用户Id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return boolean
     */
    @Override
    public boolean updateUserPassword(String username, String oldPassword, String newPassword) {
        //收集用户信息
        CustomUsernamePasswordToken usernamePasswordToken = new CustomUsernamePasswordToken(username, oldPassword, LoginType.USER.toString());
        //获取用户主体 subject 当前登陆用户（shiro）
        Subject subject = SecurityUtils.getSubject();
        try {
            // 验证旧密码是否可用
            subject.login(usernamePasswordToken);
            //获取用户信息
            User user = (User) subject.getPrincipal();
            User updateUser = new User();
            updateUser.setUserId(user.getUserId());
            updateUser.setUserName(username);
            updateUser.setPassword(newPassword);
            // 添加新密码
            remoteUserService.update(updateUser);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
